// user和用户相关的模块

// 导入本地存储token方法
import { getToken, setToken, removeToken } from '@/utils/auth'

// 导入api
import { login, getUserInfo, getUserDetailById } from '@/api/user'
const state = {
  token: getToken() || null,
  userInfo: {}
}

const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  //   移除token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 清除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登陆请求
  async userLogin(store, data) {
    const res = await login(data)
    store.commit('setToken', res.data)
  },
  //  获取用户信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    // console.log(res.data.userId)
    store.commit('setUserInfo', res.data)
    const detailInfo = await getUserDetailById(res.data.userId)
    // console.log(detailInfo)
    store.commit('setUserInfo', { ...res.data, ...detailInfo.data })
  },
  // 移除token和用户信息
  userLogout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

